function DGrid  ( name )
{
	this.name = name;
	this._rows = [];
	this.rows_ref = {};
	this._dest_div = null;

	DGrid._instances [ name ] = this;

	this.events = {
		"change" : null
	};
}

DGrid._instances = {};

DGrid.templates = {
	"dgrid-row" : '<div class="dgrid_main"><div class="dgrid_box" id="%(_id)s"></div>%(_html)s</div>'
};

DGrid.get = function ( instance_name )
{
	return DGrid._instances [ instance_name ];
};

DGrid.prototype.add = function ( row_html, info )
{
	var pos = this._rows.length;
	var n = this._mk_id ( pos );
	var s = String.formatDict ( DGrid.templates [ 'dgrid-row' ], { "_id" : n, "_html" : row_html } ); 

	if ( ! info ) info = pos;
	
	this._rows.push ( s );
	this.rows_ref [ pos ] = info;
};

DGrid.prototype.clear = function ()
{
	this._rows = [];
	this.rows_ref = {};
};

DGrid.prototype._mk_id = function ( n )
{
	return "dgrid:" + this.name + ":" + n;
};

DGrid.prototype._init = function ()
{
	DragBoxManager.target_class = "dgrid_container";
	DragBoxManager.container_class = "dgrid_main";
	DragBoxManager.box_class = "dgrid_box";

/*
	drag.container_class = "dgrid_main";
	drag.handle_class = "dgrid_box";
*/

	var self = this;
	DragBoxManager.events [ 'change' ] = function ( v ) { self._evt_change ( v ); };
	DragBoxManager.events [ 'start' ] = function ( v ) { DragBoxManager._iter_dom ( document.body ); return true; };
	DragBoxManager.init ( true );
};

DGrid.prototype._evt_change = function ( obj )
{
	var cnt = obj.parentNode;
	var elements = cnt.getElementsByTagName ( "div" );
	var t, l = elements.length, el, pos;

	this._rows = [];

	for ( t = 0; t < l; t ++ )
	{
		el = elements [ t ];
		if ( el.className != "dgrid_box" ) continue;

		pos = el.id.split ( ":" ) [ 2 ];
		this._rows.push ( this.rows_ref [ parseInt ( pos ) ] );
	}

	if ( this.events [ 'change' ] ) this.events [ 'change' ] ( this );
};

DGrid.prototype.render = function ( dest_div )
{
	var s = new String.buffer ();
	var t, l = this._rows.length;

	if ( ! dest_div ) dest_div = this._dest_div;
	this._dest_div = dest_div;

	s.add ( '<div id="dgrid:' + this.name + '" class="dgrid_container">' );
	for ( t = 0; t < l; t ++ )
		s.add ( this._rows [ t ] );

	s.add ( '</div>' );

	$( dest_div, s.toString () );

	this._init ();
};

DGrid.prototype.get_list = function ()
{
	var res = [];
	var elems = $c ( 'div', 'dgrid_box' );
	var t, l = elems.length, pos, el;

	for ( t = 0; t < l; t ++ )
	{
		el = elems [ t ];
		pos = el.id.split ( ":" ) [ 2 ];

		res.push ( this.rows_ref [ parseInt ( pos ) ] );
	}

	return res;
};
